package com.lemon.cloud.security.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lemon.cloud.comm.model.ResultMsg;
import com.lemon.cloud.comm.po.SocialParams;
import com.lemon.cloud.comm.po.SocialUser;
import com.lemon.cloud.mp.feign.MpFeign;
import com.lemon.cloud.security.enums.GrantTypeEnum;
import com.lemon.cloud.security.model.SecurityUser;
import com.lemon.cloud.security.service.SocialMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class SocialMpServiceImpl implements SocialMpService {

    @Autowired
    private MpFeign mpFeign;

    @Override
    public UserDetails loadUserByUsername(String appIdCodeSateJson) throws UsernameNotFoundException {
        if (StrUtil.isEmpty(appIdCodeSateJson)) {
            return null;
        }
        SocialParams socialParams = JSONObject.toJavaObject(JSON.parseObject(appIdCodeSateJson), SocialParams.class);
        try {
            ResultMsg<SocialUser> rsg = mpFeign.getSocialUser(socialParams);
            SocialUser socialUser = rsg.getData();
            //公众号暂时没有权限
            return getUserDetails(socialUser, null);
        }catch (Exception e){
            return null;
        }
    }

    @Override
    public UserDetails loadUserByUser(SecurityUser securityUser) {
        SocialUser socialUser = securityUser.getSocialUser();
        if (socialUser==null){
            return null;
        }
        ResultMsg<SocialUser> rsg = mpFeign.getSocialUserByOpenId(socialUser.getProviderUserId());
        //公众号暂时没有权限
        return getUserDetails(rsg.getData(), null);
    }

    @Override
    public boolean support(String clientId, String grantType) {
        return GrantTypeEnum.WECHAT_MP_CODE.getType().equals(grantType);
    }

}
